package com.taocyb.web.uc;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.taocyb.bean.uc.RegisterBean;
import com.taocyb.commons.uc.entity.User;
import com.taocyb.commons.uc.entity.UserDetail;
import com.taocyb.commons.uc.service.UserService;
import com.taocyb.framework.mail.MailService;
import com.taocyb.framework.utils.BeanMapper;
import com.taocyb.framework.utils.Servlets;
import com.taocyb.web.BaseController;

/**
 * 用户注册
 */
@Controller
@RequestMapping(value = "/uc/register")
public class RegisterController extends BaseController{

	@Autowired
	private MailService mailService;
	
	@Autowired
	private UserService userService;
	
	/**
	 * 注册页面
	 */
	@RequestMapping(method=RequestMethod.GET)
	public String index(){
//		Mail mail = new Mail();
//		mail.setFrom("Disobey@163.com");
//		mail.setFromAlias("淘城友帮");
//		mail.setTo(new String[]{"lyd8935@163.com"});
//		mail.setSubject("欢迎注册淘城友帮");
//		mail.setContent("您好，欢迎进入淘城友帮");
//		mailService.sendMime(mail);

		return "uc/register-index";
	}
	
	/**
	 * 提交注册资料 
	 */
	@RequestMapping(method = RequestMethod.POST)
	public String register(@Valid RegisterBean bean, BindingResult bindingResult, HttpServletRequest request, Model model){
		if(bindingResult.hasErrors()){
			Map<String, Object> errorMap = new HashMap<String, Object>();
			for(ObjectError objectError : bindingResult.getAllErrors()){
				FieldError fieldError = (FieldError)objectError;
				errorMap.put(fieldError.getField(),  fieldError.getDefaultMessage());
			}
			
			model.addAttribute("errorMap", errorMap);
			model.addAttribute("bean", bean);
			return this.index();
		}else{
			String registerIp = Servlets.getRemoteIp(request);
			
			User user = BeanMapper.map(bean, User.class);
			UserDetail userDetail = BeanMapper.map(bean, UserDetail.class);
			
			user.setNickName(user.getLoginName());
			user.setRegisterIp(registerIp);
			
			userService.saveUser(user, userDetail);
			return "redirect:/";
		}
	}     
}